package com.charmzenus.it.zuul.utils;

import com.charmzenus.it.zuul.base.MyErrorException;
import com.charmzenus.it.zuul.constants.CodeNumber;
import com.charmzenus.it.zuul.dto.BaseResponseDTO;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);


    /**
     * 将JAVA对象转换成JSON字符串
     *
     * @param obj
     * @return
     */
    public static String O2J(Object obj) {
        return O2J(obj, true);
    }

    /**
     * 将JAVA对象转换成JSON字符串
     * @param obj       格式化对象
     * @param hasNull   true 就会把null值也传回去， false则不会
     * @return
     */
    public static String O2J(Object obj, boolean hasNull) {

        try {
            ObjectMapper mapper = new ObjectMapper();
            // true 就会把null值也传回去， false则不会
            if (!hasNull) mapper.setSerializationInclusion(Include.NON_NULL);
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }

    /**
     * 将JSON字符串转换成JAVA对象
     *
     * @param obj
     * @param jsonString
     * @return
     */
    public static <T> T J2O(Class<T> obj, String jsonString) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(jsonString, obj);
        } catch (IOException e) {
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }

    public static <T> T J2O(TypeReference typeReference, String jsonString) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonString, typeReference);
        } catch (Exception e) {
            logger.error("格式化参数异常", e);
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }


    public static <T> String errorJson(T data, String message) {
        return formatJson(CodeNumber.error_normal, data, message);
    }

    public static <T> String formatJson(int code, T data, String message) {

        BaseResponseDTO<T> json = new BaseResponseDTO<>();
        json.setCode(code);
        json.setData(data);
        json.setMsg(message);
        return O2J(json);
    }
}
